<template>
  <div class="cateDialog">
    <el-dialog :title="title" :visible.sync="dialogStatus" :before-close="handleClose">
      <el-form ref="form" :model="category" :rules="rules" label-width="80px">
        <el-form-item label="文章分类" prop="categories">
          <el-select multiple v-model="category.categories">
            <el-option v-for="item in categories" :key="item._id" :label="item.name" :value="item._id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="category.title"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="poster">
          <el-upload
            class="avatar-uploader"
            :action="actionUrl()"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="category.poster" :src="category.poster" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="body">
          <!-- <el-input v-model="category.body"></el-input> -->
          <vue-editor v-model="category.body" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
        </el-form-item>
        <el-form-item>
          <el-button @click="save('form')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { VueEditor } from "vue2-editor";
export default {
  props: ["dialogVisible", "title", "dialogId", "parents"],
  components: {
    VueEditor
  },
  data() {
    return {
      category: {
        categories: "",
        title: "",
        body: "",
        poster: ""
      },
      rules: {
        categories: [{required: true, message: '请选择分类', trigger: 'blur'}],
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        body: [{required: true, message: '请输入内容', trigger: 'blur'}],
        poster: [{required: true, message: '请选择封面', trigger: 'blur'}]
      },
      categories: [] //分类
    };
  },
  methods: {
    handleClose() {
      this.category.categories = "";
      this.category.title = "";
      this.category.body = "";
      this.category.poster = "";
      this.$emit("close", false);
    },
    save(formName) { //保存
      this.$refs[formName].validate(async (valid)=>{
        if (valid) {
          if (this.dialogId) { //修改
            await this.$http.put("rest/articles/" + this.dialogId, this.category);
          } else { //新增
            await this.$http.post("rest/articles", this.category);
          }
          this.$refs[formName].resetFields()
          this.handleClose();
          this.$emit("getCategory");
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async getCateById(id) {
      //通过id获取分类信息
      const res = await this.$http.get("rest/articles/" + id);
      this.category = res.data;
      this.$forceUpdate();
    },
    handleAvatarSuccess(res, file) { //上传成功回显
      this.$refs['form'].validate(async (valid)=>{
        console.log(valid)
      })
      // 上传图片成功后清除验证
      this.$refs['form'].clearValidate('poster')
      this.category.poster = res.url;
    },
    beforeAvatarUpload(file) { //上传前检验
      const isJPG = file.type.includes('image');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("封面必须是图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async getCategories() { //获取分类信息
      const res = await this.$http.get("rest/categories");
      this.categories = res.data
    },
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) { //富文本自定义上传图片
      const formData = new FormData();
      formData.append("file", file);
      const res = await this.$http.post('upload',formData);
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    }
  },
  watch: {
    dialogStatus(val) {
      val && this.getCategories()
      val && this.dialogId && this.getCateById(this.dialogId);
    }
  },
  computed: {
    dialogStatus() {
      return this.dialogVisible;
    }
  }
};
</script>
<style lang='scss' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>